import { ConfigFileAttrs } from "@/types";

interface StorageDataTypes {
  data: any,
  expired?: number
}

class HStorage {
  private cecheTime: number = 24 * 60 * 60;
  static WebConfKey = "web-conf";
  constructor() {

  }

  /**
   * 保存localStorage
   * @param key 
   * @param value 
   * @param expired 
   */
  setItem(key: string, value: any, expired?: number) {
    const data = this.transToStorageData(value, expired);
    window.localStorage.setItem(key, JSON.stringify(data));
  }

  /**
   * 获取 保存localStorage
   * @param key 
   * @returns 
   */
  getItem(key: string): StorageDataTypes {
    let ret = this.transToStorageData(undefined);
    try {
      const item = window.localStorage.getItem(key);
      if (item) {
        ret = JSON.parse(item);
      }
    } catch(err) {
      throw err;
    }

    return ret
  }

  /**
   * 转换为 storage 数据
   * @param data 
   * @param expired 
   * @returns 
   */
  private transToStorageData(data: any, expired?: number): StorageDataTypes {
    return {
      data,
      expired
    }
  }
}

class LoginAuthStorage {
  private LoginAuthKey = "Authorization";

  getToken(): string {
    const { data } = storage.getItem(this.LoginAuthKey);
    return data
  }

  setToken(value: string) {
    storage.setItem(this.LoginAuthKey, value);
  }
}

export const storage = new HStorage();

/** 读取配置数据 */
export function getConfigOptions(): ConfigFileAttrs {
  const { data } = storage.getItem(HStorage.WebConfKey);
  return data;
}

export default HStorage;
export const loginAuthStorage = new LoginAuthStorage();